package com.weiiew.backend.controller;

import com.weiiew.backend.utils.ApiResponse;
import com.weiiew.backend.utils.HotkeyRepository;
import com.weiiew.backend.utils.listener.FirstKeyListener;
import com.weiiew.backend.utils.listener.HotkeyListenerManager;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * @author 魏锴
 * @since 2025/5/1
 */
@RestController
@RequestMapping("/setting")
public class SettingController {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    @Autowired
    private HotkeyListenerManager manager;
    @Autowired
    private FirstKeyListener firstKeyListener;
    @Autowired
    private HotkeyRepository repository;

    @PostMapping("/list")
    public ApiResponse getHotKeyList() {
        return ApiResponse.ok("获取成功").append("list", repository.getHotkeys());
    }

    @PostMapping("/firstKey")
    public ApiResponse getFirstKey(String key) {
        firstKeyListener.startFirstKeyListener(keyInfo -> {
            repository.updateHotkey(key, keyInfo.getKeyCode().getNativeCode());
            messagingTemplate.convertAndSend("/topic/hotkey", repository.getHotkeys());
        });
        return ApiResponse.ok("监听已启动");
    }

    @GetMapping("/name/{desc}")
    public ApiResponse getKeyByDesc(@PathVariable String desc) {
        return ApiResponse.ok("获取成功")
                .append("key", NativeKeyEvent.getKeyText(repository.getHotkey(desc)));
    }
}
